const {
  NAME_OR_PASSWORD_IS_REQUIRED,
  NAME_IS_NOT_EXISTS,
  NAME_IS_NOT_INCORRENT,
  UNAUTHORIZATION,
} = require("../config/error");
const jwt = require("jsonwebtoken");
const { PRIVATE_KEY, PUBLIC_KEY } = require("../config/screct");
const userService = require("../service/user.service");

const md5password = require("../utils/md5password");
const verifyLogin = async (ctx, next) => {
  const { name, password } = ctx.request.body;

  // 验证用户密码是否填写
  if (!name || !password) {
    ctx.app.emit("error", NAME_OR_PASSWORD_IS_REQUIRED, ctx);
    return;
  }

  // 验证用户是否存在
  const users = await userService.findUser(name);
  if (!users[0]) {
    ctx.app.emit("error", NAME_IS_NOT_EXISTS, ctx);
    return;
  }

  // 验证密码是否正确
  if (users[0].password !== md5password(password)) {
    ctx.app.emit("error", NAME_IS_NOT_INCORRENT, ctx);
    return;
  }
  ctx.user = users[0];
  next();
};

const verifyAuth = async (ctx, next) => {
  const authorization = ctx.headers.authorization;

  if (!authorization) {
    ctx.app.emit("error", UNAUTHORIZATION, ctx);
    return;
  }

  const token = authorization.replace("Bearer ", "");

  try {
    const result = jwt.verify(token, PUBLIC_KEY, {
      algorithms: ["RS256"],
    });
    // 验证出来的结果给到body
    // console.log("result,", result);
    ctx.user = result;

    await next();
  } catch (e) {
    ctx.app.emit("error", UNAUTHORIZATION, ctx);
  }
};

module.exports = {
  verifyLogin,
  verifyAuth,
};
